/*
Package controllers 简单的认证服务 也许以后可能用OAuth2
*/
package controllers

import (
	"net/http"
	"pegasus/datatypes"
	"pegasus/repositories"
	"pegasus/services"
	"pegasus/utils"
)

//Authorize Authorize controller 授权通常是独立的服务器 以后要拆分
type Authorize struct {
	utils.ILogger
}

//Logout 退出登录 此时应该主动把websocket 长链接给关掉 但通常授权服务器和websocket不是同一个服务器
//很难保证
func (at *Authorize) Logout(si datatypes.SIContent, sm services.SessionService) *Response {
	sm.Remove(si.Token())
	return NewResponseSucc(nil)
}

//LoginBM 登录请求
type LoginBM struct {
	User     string
	Password string
}

//Login 登录
func (at *Authorize) Login(response http.ResponseWriter, sm services.SessionService, ur *repositories.UserRepo, bm *LoginBM, log *repositories.LogRepo) *Response {
	if bm.User == "" || bm.Password == "" {
		return NewResponseErr(ErrorArgument, ErrorArgumentMsg)
	}
	bean := ur.Find(bm.User)
	if bean == nil {
		return NewResponseErr(ErrorGeneric, "帐号或密码错误")
	}
	if ok := ur.CheckPassword(bean.Password, bm.Password); !ok {
		return NewResponseErr(ErrorGeneric, "帐号或密码错误")
	}
	token := sm.Add(bean.ID)
	//头部添加touken
	response.Header().Set(utils.Authorization, token)
	log.AddLogin(bean.ID)
	return NewResponseSucc(nil)
}
